// import { user } from '@/services/api'
import router from 'umi/router'
// import { routerRedux } from 'dva/router'
import settings from '@/settings'

import { formatterData } from '@/components/SiderMenu'
import { loguser, logout } from '@/services/api'

export default {
	namespace: 'app',
	state: {
		user: {},
		menu: [],
		pathname: '',
		// user: {}
	},
	reducers: {
		updateState(state, { payload }) {
			return {
				...state,
				...payload
			}
		},
		// saveCurrentUser(state, action) {
		// 	return {
		// 		...state,
		// 		user: action.payload || {}
		// 	}
		// }
	},
	subscriptions: {
		setupHistory({
			dispatch,
			history
		}) {
			history.listen(location => {
				dispatch({
					type: 'updateState',
					payload: {
						pathname: location.pathname
					}
				})
			})
		},
		setup({ dispatch, history }) {
			// history.listen(({pathname, search}) => {
				
			// })
			// dispatch({
			// 	type: 'query'
			// })
			// history.listen(({
			// 	pathname
			// }) => {
			// 	if (pathname !== '/login') {
			// 		dispatch({
			// 			type: 'query'
			// 		})
			// 	}
			// })
		}
	},
	effects: {
		// *query({
		// 	payload
		// }, {
		// 	call,
		// 	put,
		// 	select
		// }) {
		// 	const {
		// 		pathname
		// 	} = yield select(_ => _.app)
			
		// 	if (pathname.toLowerCase() !== '/login') {
		// 		const { data } = yield call(user, payload)
		// 		if (data.code === 200) {
		// 			yield put({
		// 				type: 'saveCurrentUser',
		// 				payload: data.data
		// 			})
		// 			// router.push({
		// 			// 	pathname: '/'
		// 			// })
		// 		} else {
		// 			router.push({
		// 				pathname: '/login'
		// 			})
		// 			// yield put(routerRedux.push('/login'))
		// 		}
		// 	}
		// },
		*menu({
			payload
		}, { put, select }) {
			const {
				routes
			} = payload
			const {
				authorities = []
			} = yield select(_ => _.app.user || {})

			const menu = formatterData(routes, authorities)

			yield put({
				type: 'updateState',
				payload: {
					menu
				}
			})
		},
		*fetchCurrent({
			payload
		}, {
			call,
			put
		}) {
			const { data } = yield call(loguser, payload)
			yield put({
				type: 'updateState',
				payload: {
					user: data
				}
			})
		},
		*logout(_, {
			call, put
		}) {
			const { code } = yield call(logout)
			if (code === settings.code) {
				yield put({
					type: 'updateState',
					payload: {
						user: {}
					}
				})
				router.push('/login')
			}
		}
	}
}